package com.ljx.demo5.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DataBaseUtil {
    public static Connection getConnection() throws SQLException {
        Connection connection = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection =
                    DriverManager.getConnection("jdbc:mysql://localhost:3306/newssys?useUnicode=true&characterEncoding = gb2312", "root", " 123456");
        } catch (ClassNotFoundException e) {
            throw new SQLException("数据库连接异常");
        }
        return connection;
    }

    public static int executeUpdate(String sql, Object[] params) throws SQLException {
        int j = 0;
        Connection connection = getConnection();
        try {
            connection = DataBaseUtil.getConnection();
            PreparedStatement pst = connection.prepareStatement(sql);
            if (params != null) {
                for (int i = 0; i < params.length; i++) {
                    Object param = params[i];
                    pst.setObject(i + 1, param);
                }
            }
            j = pst.executeUpdate();
        } finally {
            if (connection != null) {
                connection.close();
            }
        }
        return j;
    }


}
